﻿var CountryValidationClientSideHide = false;
var PageNumber = 1;
var IsSearchView = false;
var CountryIDView = 0;
var IsDeleteView = false;
var CountryComElem = null;
var CountryComElemVal = null;
var CountryTimerId = null;
$(document).ready(function () {
    var path = window.location.pathname;
    if (path.indexOf("SetupCountry") != -1) {
        $.validator.addMethod("SetupCountryRequireds", $.validator.methods.required, Messages["SetupCountryRequireds"]);
        $.validator.addMethod("SetupCountryMaxLength3", $.validator.methods.maxlength, Messages["SetupCountryMaxLength3"]);
        $.validator.addMethod("SetupCountryMaxLength20", $.validator.methods.maxlength, Messages["SetupCountryMaxLength20"]);
        $.validator.addMethod("SetupCountryMaxLength30", $.validator.methods.maxlength, Messages["SetupCountryMaxLength30"]);
        $.validator.addClassRules({
            Required: {
                SetupCountryRequireds: true,
            },
            MaxLength3: {
                SetupCountryMaxLength3: 3,
            },
            MaxLength20: {
                SetupCountryMaxLength20: 20,
            },
            MaxLength30: {
                SetupCountryMaxLength30: 30,
            },
        });

        $('#LoadCountryDetailsForm').validate();
        LoadCountryGrid();
    }
});
$(document).on('change', '.ChangedCountryElements', function () {
    $('#CountryDetailsSaveBtn').addClass('BackColorRed');
});
$(document).on('change', '.CountryAddElementChange', function () {
    $('#CountryAddBtn').addClass('BackColorRed');
});
function DeleteCountry(CountryID) {
    jConfirm('Are you sure you want to delete this Country?', 'Warning!', function (retVal) {
        if (retVal == true) {
            CountryIDView = CountryID;
            IsDeleteView = true;
            LoadCountryGrid();
        }
    });
}
function AddNewCountry() {
    CountryValidationClientSideHide = false;
    $.ajax({
        url: urls["SetupAddNewCountry"],
        type: 'GET',
        success: function (data) {
            $("#AddNewCountryDiv").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            IsDeleteView = false;
            AddNewCountryPopUp("AddNewCountryDiv");
        }
    });
}
$(document).on('click', '#CountryMoreBtn', function () {
    PageNumber = PageNumber + 1;
    IsDeleteView = false;
    LoadCountryGrid();
});
$(document).on('click', '#CountrySearchBtn', function () {
    IsSearchView = true;
    IsDeleteView = false;
    LoadCountryGrid();
});
function AddNewCountryPopUp(PopUpDiv) {
    $.colorbox({
        width: "600px",
        height: "245px",
        inline: true,
        href: "#" + PopUpDiv,
        onComplete: function () {
            $("#" + PopUpDiv).show();
        },
        onClosed: function () {
            $("#" + PopUpDiv).hide();
        }
    });
}
$(document).on('click', '#CountryAddBtn', function () {
    var $form = $('#AddNewCountryForm');
    if ($form.valid()) {
        CountryValidationClientSideHide = false;
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: $form.serialize(),
            beforeSend: function (xhr) {
                xhr.overrideMimeType('text/plain; charset=x-user-defined');
            },
            success: function (data) {
                if (data.indexOf("Error") != -1)
                    jAlert(data, "Error");
            },
            error: function (xhr) {
                jAlert(xhr.statusText, "Error");
            },
            complete: function () {
                $('#CountryAddBtn').removeClass('BackColorRed')
                jAlert("Data SuccessFully Saved:", "Successful");
                $('#cboxClose').click();
                IsDeleteView = false;
                LoadCountryGrid();
            }
        });
    }
    else
        CountryValidationClientSideHide = true;
});

$(document).on('click', '#CountryDetailsSaveBtn', function () {
    var $form = $('#LoadCountryDetailsForm');
    if ($form.valid()) {
        if ($form[0].length > 0) {
            $.ajax({
                url: $form.attr('action'),
                type: $form.attr('method'),
                data: $form.serialize(),
                beforeSend: function (xhr) {
                    xhr.overrideMimeType('text/plain; charset=x-user-defined');
                },
                success: function (data) {
                    if (data.indexOf("Error") != -1)
                        jAlert(data, "Error");
                },
                error: function (xhr) {
                    jAlert(xhr.statusText, "Error");
                },
                complete: function () {
                    $('#CountryDetailsSaveBtn').removeClass('BackColorRed')
                    jAlert("Data SuccessFully Saved:", "Successful");
                    IsDeleteView = false;
                    LoadCountryGrid();
                }
            });
        }
        else
            jAlert("You have not data to save:", "Attention!");
    }
});
function LoadCountryGrid() {
    var SetupCountriesGridViewModel = {
        CountryCodeText: $("#CountryCodeText").val(),
        CountryNameText: $("#CountryNameText").val(),
        NationalityText: $("#NationalityText").val(),
        PageNum: parseInt(PageNumber),
        IsSearch: IsSearchView,
        IsDelete: IsDeleteView,
        CountryID: parseInt(CountryIDView),
        IsActiveSearch: $("#IsActiveSearch").val(),
    };

    var DTO = JSON.stringify(SetupCountriesGridViewModel);
    $.ajax({
        url: urls["SetupLoadCountriesGrid"],
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: DTO,
        success: function (data) {
            $("#SetupCountryGrid").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
        }
    });
}
// text element complete text 
$(document).on('input', '.QuotaTxtComplete', function () {
    if (CountryTimerId == null) {
        CountryComElem = $(this).attr('id');
        CountryComElemVal = $("#" + CountryComElem).val();
        CountryTimerId = setInterval(function () {

            var keyword = $("#" + CountryComElem).val();
            if (keyword == CountryComElemVal) {
                var PropName = "";
                if (CountryComElem.indexOf("CountryCodeText") != -1)
                    PropName = "CountryCodeText";
                if (CountryComElem.indexOf("CountryNameText") != -1)
                    PropName = "CountryNameText";
                if (CountryComElem.indexOf("NationalityText") != -1)
                    PropName = "NationalityText";

                var position = $("#" + CountryComElem).offset();
                position.top = position.top + $("#" + CountryComElem).height() + 5;
                $.ajax({
                    url: urls["SetupAutoComplete"],
                    data: { 'PropName': PropName, 'keyword': keyword },
                    type: 'POST',
                    success: function (data) {
                        $("#AutoCompleteDiv").html(data);
                        var width = $("#" + CountryComElem).css("width");
                        $("#AutoCompleteDiv").css("width", width);
                        $("#AutoCompleteDiv").show();
                        $("#AutoCompleteDiv").offset(position);
                    },
                    error: function (xhr) {
                        jAlert(xhr.statusText, "Error");
                    },
                    complete: function () {
                        clearInterval(CountryTimerId);
                        CountryTimerId = null;
                    }
                });
            }
            else
                CountryComElemVal = keyword;
        }, 600);
    }
});
$(document).on('click', '.QuotaAutoCompleteDivClose', function () {
    $(this).parent().parent().hide();
});
function htmlDecode(value) {
    return $('<div/>').html(value).text();
}
function AutoCompleteRowClick(key, val) {
    val = htmlDecode(val);
    $("#" + CountryComElem).val(val);
    if (CountryComElem.indexOf("CountryCodeText") != -1)
        $("#" + CountryComElem).next().val(key);
    if (CountryComElem.indexOf("CountryNameText") != -1)
        $("#" + CountryComElem).next().val(key);
    if (CountryComElem.indexOf("NationalityText") != -1)
        $("#" + CountryComElem).next().val(key);
    $("#AutoCompleteDiv").hide();
}

var originalClose = $.colorbox.close;
$.colorbox.close = function () {
    if ($('#CountryAddBtn').hasClass('BackColorRed')) {
        jConfirm(Messages["ClosePopUp"], Messages["ClosePopUpTitle"], function (retVal) {
            if (retVal == true) {
                $("#AddNewCountryForm").empty();
                LoadCountryGrid();
                originalClose();
            }
        });
    }
    else {
        $("#AddNewCountryForm").empty();
        LoadCountryGrid();
        originalClose();
    }
};
$(document).on('change', '.ElementsForValidation', function () {
    if ($(this).valid()) {
        $(this).closest("form").find("#errorMessageClient").text("");
    }
    else
        $(this).closest("form").find("#errorMessageServer").hide();
    if (CountryValidationClientSideHide) {
        if ($(this).closest("form").valid()) {
            $(this).closest("form").find("#errorMessageClient").text("");
        }
    }
    else if ($(this).valid()) {
        var elements = "#" + $(this).closest("form").attr("id") + " .error";
        $(elements).not('label').each(function () {
            $(this).valid();
        });
    }
});
$(document).on('change', '.ForValidation', function () {
    if ($(this).valid)
        $(this).removeClass('table_inputs_Unvalidated');
    if ($(this).closest("form").valid()) {
        $(this).closest("form").find("#errorMessageClient").text("");
        var elements = "#" + $(this).closest("form").attr("id") + " .error";
        $(elements).not('label').each(function () {
            if ($(this).valid())
                $(this).removeClass('table_inputs_Unvalidated');
        });
    }
    else
        $(this).closest("form").find("#errorMessageServer").hide();
});